package com.mall.service.user;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mall.client.user.LogisticsService;
import com.mall.common.util.MD5Util;
import com.mall.custom.dao.read.LogisticsReadMapper;
import com.mall.custom.dao.write.LogisticsWriteMapper;
import com.mall.pojo.Logistics;
import com.mall.pojo.LogisticsExample;
import com.mall.pojo.LogisticsExample.Criteria;
@Service
public class LogisticsServiceImpl implements LogisticsService {
	
	@Autowired
	private LogisticsReadMapper logisticsReadMapper;

	@Autowired
	private LogisticsWriteMapper logisticsWriteMapper;
	

	@Override
	public Logistics getLogisticsByLogisticsIdAndLogisticsCompany(String logisticsId, String logisticsCompany,Integer onlyKey) {

		if (StringUtils.isBlank(logisticsId) || StringUtils.isBlank(logisticsCompany)) {
			return null;
		}

		Logistics logistics = null;
		String dbContent = "";

		LogisticsExample example = new LogisticsExample();
		Criteria criteria = example.createCriteria();
		criteria.andLogisticsCompanyEqualTo(logisticsCompany);
		criteria.andLogisticsIdEqualTo(logisticsId);
		List<Logistics> logisticsList = this.logisticsReadMapper.selectByExample(example);
		if (logisticsList != null && logisticsList.size() > 0) {
			logistics = logisticsList.get(0);
			dbContent = logistics.getLogisticsAddress();
		}

		String kuaiDiUrl = "http://m.kuaidi100.com/query?type=" + logisticsCompany + "&postid=" + logisticsId
				+ "&id=1&valicode=&temp=";

		String urlContent = sendGet(kuaiDiUrl,null);
//		System.out.println(sendGet("http://m.kuaidi100.com/query?type=shentong&postid=3325374695980&id=1&valicode=&temp=",null));
		if (StringUtils.isBlank(urlContent)) {
			return getLogisticsFromLogisticsCompanyAndLogisticsId(logisticsId, logisticsCompany);
		}

		String urlContentMD5 = MD5Util.GetMD5Code(urlContent);
		String dbContentMD5 = MD5Util.GetMD5Code(dbContent);
		if (dbContentMD5.equals(urlContentMD5)) {
			return logistics;
		}

		JSONObject jsonObject = JSON.parseObject(urlContent);
		if (!jsonObject.getString("message").equals("ok")) {
			return logistics;
		}

		Logistics logistics4DB = new Logistics();
		//logistics4DB.setGmtCreate(new Date());
		logistics4DB.setGmtModify(new Date());
		logistics4DB.setLogisticsCompany(logisticsCompany);
		logistics4DB.setLogisticsAddress(urlContent);
		logistics4DB.setLogisticsId(logisticsId);
		logistics4DB.setStatus(0);
		logistics4DB.setType(0);
		logistics4DB.setCommOnlyKey(onlyKey);
		if (logistics != null) {
			logistics4DB.setId(logistics.getId());
			this.logisticsWriteMapper.updateByPrimaryKeySelective(logistics4DB);
		} else {
			logistics4DB.setGmtCreate(new Date());
			this.logisticsWriteMapper.insertSelective(logistics4DB);
		}

		return logistics4DB;

	}

	private Logistics getLogisticsFromLogisticsCompanyAndLogisticsId(String logisticsId, String logisticsCompany) {
		LogisticsExample example = new LogisticsExample();
		Criteria criteria = example.createCriteria();
		criteria.andLogisticsCompanyEqualTo(logisticsCompany);
		criteria.andLogisticsIdEqualTo(logisticsId);
		List<Logistics> logisticsList = this.logisticsReadMapper.selectByExample(example);
		if (logisticsList == null || logisticsList.size() <= 0) {
			return null;
		}

		return logisticsList.get(0);
	}

	public static void main(String[] args) {
		System.out.println(sendGet("http://m.kuaidi100.com/query?type=shentong&postid=3325374695980&id=1&valicode=&temp=", null));
		
		//new LogisticsServiceImpl().getLogisticsByLogisticsIdAndLogisticsCompany("3325374695980", "shentong");
	}

	public static String sendGet(String url, String param) {
		String result = "";
		BufferedReader in = null;
		try {
			String urlNameString = url + "?" + param;
			URL realUrl = new URL(urlNameString);
			// 打开和URL之间的连接
			URLConnection connection = realUrl.openConnection();
			// 设置通用的请求属性
			connection.setRequestProperty("accept", "*/*");
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// 建立实际的连接
			connection.connect();
			// 获取所有响应头字段
			Map<String, List<String>> map = connection.getHeaderFields();
			// 遍历所有的响应头字段
			// for (String key : map.keySet()) {
			// System.out.println(key + "--->" + map.get(key));
			// }
			// 定义 BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			System.out.println("发送GET请求出现异常！" + e);
		}
		// 使用finally块来关闭输入流
		finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (Exception e2) {
				//log.error(e2.getMessage(), e2);
			}
		}
		return result;
	}

}
